package com.greatwall.hip.cms.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;

/**
 * @author TianLei
 * @version V1.0
 */
@Component
public class JWTTokenUtil {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private static JWTTokenUtil jwtUtil;

    @Autowired
    JWTProperties jwtProperties;


    @PostConstruct
    public void init() {
        jwtUtil = this;
        jwtUtil.jwtProperties = this.jwtProperties;
    }

    static String resolveToken(HttpServletRequest request) { return request.getHeader(JWTConstants.REQUEST_AUTH_HEADER);}

    /**
     * 生成签名
     * @param username 用户名
     * @param secret   用户密码，使用Algorithm.HMAC256(secret)作为签发token的秘钥。若签发token时都使用同一个秘钥，会存在秘钥泄露的风险。
     */
    public static String sign(String username, String secret) {
        Date date = new Date(System.currentTimeMillis()+ jwtUtil.jwtProperties.getTokenExpireTime() * 1000 * 60);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带username信息
        return JWT.create()
                .withClaim("loginName", username)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    // 获取用户名
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("loginName").asString();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }

    // token是否过期
    public static boolean isExpired(String token) {
        Date now = Calendar.getInstance().getTime();
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getExpiresAt().before(now);
    }

}
